import userService from "@/api/user/index";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";

// import getfarmtypelistmethod from "@/api/basic-info-manage/agricultural-type-manage";
import { accountCookie, passwordCookie } from "@/utils/cookie";
const getDefaultState = () => {
  return {
    token: getToken("token"), // 登录用户的token
    name: getToken("account"), // 登录用户名
    status: false, // 用户状态有无更改 可改变路由
    userInfo: {
      account: '',
      password: ''
    } // 存储登录的用户名和密码
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  SET_STATUS: (state, status) => {
    state.status = status;
  },
  SET_USERINFO: (state, status) => {
    state.userInfo = status;
  }
};

const actions = {
  login({ commit }, userInfo) {
    let infoo = JSON.parse(JSON.stringify(userInfo));
    commit("SET_USERINFO", userInfo);
    // setToken("userInfo", infoo);
    setToken("userInfo", JSON.stringify({ ...infoo, account: accountCookie(infoo.account), password: passwordCookie(infoo.password) }));
    const { account, password } = userInfo;
    return new Promise((resolve, reject) => {
      userService
        // .login({ account: account.trim(), password: password, systemMark: "DB_TDW1_SC" })
        .login({ username: account.trim(), password: password })
        .then(async response => {
          if (response.code === 1) {
            const data = response.data;
            setToken("token", data.accessToken);
            setToken("username", data.username);
            setToken("account", account.trim());
            resolve();
          } else {
            // await userService.loginErr(account.trim())
            reject(response.msg);
            //   this.$message.warning(
            //   msg || "用户账号不存在/密码错误"
            // );
          }
        })
        .catch(async error => {
          // await userService.loginErr(account.trim())
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 删除全部本地缓存
      sessionStorage.clear();
      resetRouter(); // 重置路由
      commit("RESET_STATE"); // 重置用户数据
      resolve();
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken("token"); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  }

  // get menu
  // getAuthMenu() {
  //   return new Promise((resolve, reject) => {
  //     userService
  //       .getmenyinfo({ farmId: 32 })
  //       .then(response => {
  //         const data = response.data.menulist;
  //         console.log(data)
  //         setToken("farmmenu", data);
  //         resolve();
  //       })
  //       .catch(error => {
  //         reject(error);
  //       });
  //   })
  // }
};
export default {
  namespaced: true,
  state,
  mutations,
  actions
};
